#include "editprofiletask.h"
#include "libs/base/service/uploader.h"
#include "libs/base/utils/copyfile.h"
#include "libs/core/user/localuser.h"
#include "services/yingceservice.h"
#include "usersettings.h"
#include "yingce.h"

EditProfileTask::EditProfileTask(const yc::UserDetail& detail, const QString& avatar_path,
                                 QObject* parent)
    : yc::Task { 0, true, 0, parent }, detail_(detail), avatar_path_(avatar_path)
{
}

QString EditProfileTask::statusMessage() const
{
    return tr("Edit profile ...");
}

qint64 EditProfileTask::evaluateTotalMSecs() const
{
    return 180000;
}

void EditProfileTask::editProfile()
{
    YingCeService::instance()->changeUser(
            detail_,
            yc::ResponseHandler(
                    this, [this](const yc::Request& request, const yc::Response& response) {
                        Q_UNUSED(request)
                        if (response.status() != 200) {
                            Q_EMIT failed(yc::SERVICE_ERROR,
                                          tr("Failed to edit the profile, the error is \"%1\".")
                                                  .arg(response.msg()));
                        } else {
                            yc::LocalUser* user = YingCe::instance()->localUser();
                            user->setNickname(detail_.nickname());
                            user->setGender(detail_.gender());
                            if (!avatar_path_.isEmpty()) {
                                user->setAvatar(detail_.avatar());
                            }
                            Q_EMIT finished();
                        }
                    }));
}

void EditProfileTask::startImpl()
{
    if (avatar_path_.isEmpty()) {
        editProfile();
    } else {
        const QDir res_dir = UserSettings::instance().resDir();
        const QString new_path =
                yc::CopyFileWorker::copyTo(avatar_path_, res_dir.absolutePath(), QString());
        if (new_path.isEmpty()) {
            Q_EMIT failed(yc::LOGIC_ERROR, tr("Failed to calculate file md5."));
            return;
        }

        QFileInfo fi(new_path);
        const QString name = fi.fileName();
        detail_.setAvatar(name);
        QList<yc::UploadResource> uploads;
        uploads.push_back(yc::UploadResource { name, fi.size(), name });

        const QString service_url = UserSettings::instance().serviceUrls().cloud_upload;
        yc::Uploader* t = new yc::Uploader(YingCeService::instance(), service_url,
                                           res_dir.absolutePath(), uploads, this);
        t->setHeaders(YingCeService::instance()->headers());
        connect(t, &yc::Uploader::failed, this, [this](int error, const QString& message) {
            Q_UNUSED(error)
            Q_EMIT failed(yc::SERVICE_ERROR,
                          tr("Failed to upload the avatar, the error is \"%1\".").arg(message));
        });
        connect(t, &yc::Uploader::finished, this, &EditProfileTask::editProfile);
        t->start();
    }
}
